package com.lzl.service;

import com.lzl.constant.CommonStatusEnum;
import com.lzl.constant.TokenConstant;
import com.lzl.dto.TokenResult;
import com.lzl.responese.ResponseResult;
import com.lzl.responese.TokenResponse;
import com.lzl.util.JWTUtils;
import com.lzl.util.RedisPrefixUtils;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * //TODO
 *
 * @author zhaolinlin
 * @description //TODO
 * @createTime 2022/8/11 21:42
 */
@Service
public class TokenService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public ResponseResult refreshToken(String refreshToken) {

        TokenResult tokenResult = JWTUtils.checkToken(refreshToken);
        if(tokenResult == null){
            return ResponseResult.fail(CommonStatusEnum.TOKNE_ERROR.getCode(),CommonStatusEnum.TOKNE_ERROR.getValue());
        }
        String phone = tokenResult.getPhone();
        String identity = tokenResult.getIdentity();
        String refreshTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstant.REFRESH_TOKEN);

        String refreshTokenRedis = stringRedisTemplate.opsForValue().get(refreshTokenKey);

        if(StringUtils.isBlank(refreshTokenRedis) || !refreshToken.trim().equals(refreshTokenRedis)){
            return ResponseResult.fail(CommonStatusEnum.TOKNE_ERROR.getCode(),CommonStatusEnum.TOKNE_ERROR.getValue());
        }

        //生成双token
        String newAccessToken = JWTUtils.generatorToken(phone, identity, TokenConstant.ACCESS_TOKEN);
        String newRefreshToken = JWTUtils.generatorToken(phone, identity, TokenConstant.REFRESH_TOKEN);
        String accessTokenKey = RedisPrefixUtils.generatorTokenKey(phone, identity, TokenConstant.ACCESS_TOKEN);

        //存入redis中
        stringRedisTemplate.opsForValue().set(accessTokenKey,newAccessToken,3, TimeUnit.MINUTES);
        stringRedisTemplate.opsForValue().set(refreshTokenKey,newRefreshToken,6, TimeUnit.MINUTES);

        TokenResponse tokenResponse = new TokenResponse();
        tokenResponse.setAccessToken(newAccessToken);
        tokenResponse.setRefreshToken(newRefreshToken);

        return ResponseResult.success(tokenResponse);


    }
}
